package com.pine.app.module.security.oauth.provider.authentication;

import lombok.EqualsAndHashCode;
import lombok.ToString;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.Serializable;

/**
 * @author xiaoyuan
 * @create 2019/9/6 16:03
 **/
@EqualsAndHashCode
public class OAuth2AuthenticationDetails implements Serializable {
    private static final long serialVersionUID = -4809832298438307309L;
    public static final String ACCESS_TOKEN_VALUE = OAuth2AuthenticationDetails.class.getSimpleName() + ".ACCESS_TOKEN_VALUE";
    public static final String ACCESS_TOKEN_TYPE = OAuth2AuthenticationDetails.class.getSimpleName() + ".ACCESS_TOKEN_TYPE";
    private final String remoteAddress;
    private final String sessionId;
    private final String tokenValue;
    private final String tokenType;
    private final String display;
    private Object decodedDetails;

    public OAuth2AuthenticationDetails(HttpServletRequest request) {
        this.tokenValue = (String)request.getAttribute(ACCESS_TOKEN_VALUE);
        this.tokenType = (String)request.getAttribute(ACCESS_TOKEN_TYPE);
        this.remoteAddress = request.getRemoteAddr();
        HttpSession session = request.getSession(false);
        this.sessionId = session != null?session.getId():null;
        StringBuilder builder = new StringBuilder();
        if(this.remoteAddress != null) {
            builder.append("remoteAddress=").append(this.remoteAddress);
        }

        if(builder.length() > 1) {
            builder.append(", ");
        }

        if(this.sessionId != null) {
            builder.append("sessionId=<SESSION>");
            if(builder.length() > 1) {
                builder.append(", ");
            }
        }

        if(this.tokenType != null) {
            builder.append("tokenType=").append(this.tokenType);
        }

        if(this.tokenValue != null) {
            builder.append("tokenValue=<TOKEN>");
        }

        this.display = builder.toString();
    }

    public String getTokenValue() {
        return this.tokenValue;
    }

    public String getTokenType() {
        return this.tokenType;
    }

    public String getRemoteAddress() {
        return this.remoteAddress;
    }

    public String getSessionId() {
        return this.sessionId;
    }

    public Object getDecodedDetails() {
        return this.decodedDetails;
    }

    public void setDecodedDetails(Object decodedDetails) {
        this.decodedDetails = decodedDetails;
    }

    public String toString() {
        return this.display;
    }


}
